<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      class="pr-30px"
      ref="formRef"
      :model="formData"
      v-loading="formLoading"
      label-width="110"
      :rules="rules"
    >
      <el-form-item label="标签内容" prop="label">
        <el-input v-model="formData.label" />
      </el-form-item>
      <el-form-item label="标签答复" prop="content">
        <el-input v-model="formData.content" />
      </el-form-item>
      <el-form-item label="标签类型" prop="type" @change="stepTypeChange(formData.type)">
        <el-radio-group v-model="formData.type">
          <el-radio :label="1">步骤</el-radio>
          <el-radio :label="2">表单</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="关联子场景" prop="nextStepId" v-if="formData.type == 1">
        <el-select v-model="formData.nextStepId" placeholder="请选择" style="width: 100%">
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="item in stepNextList"
            :key="item.id"
            :disabled="item.id == formData.sceneId"
          />
        </el-select>
      </el-form-item>
      <div v-if="formData.type == 2">
        <el-row v-for="item,index in formItemList" :key="index">
          <el-form-item label="字段名称">
            <el-input placeholder="例如: 姓名" v-model="item.formLabel" />
          </el-form-item>
          <el-form-item label="表单提示">
            <el-input placeholder="例如: 请输入您的姓名" v-model="item.formPlaceHolder" />
          </el-form-item>
          <el-button text type="danger" @click="delFormItem(index)">删除</el-button>
        </el-row>
      </div>
      <el-form-item v-if="formData.type == 2">
        <el-button @click="addFormItem" type="primary" class="mt-10px">添加表单项</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as SceneApi from '@/api/service/scene/index'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  label: undefined,
  content: undefined,
  type: 1,
  nextStepId: undefined,
  sceneId: undefined
})
const formRef = ref() // 表单 Ref
const rules = reactive<FormRules<FormRef>>({
  label: [
    { required: true, message: '请填写标签名称', trigger: 'blur' },

    { min: 1, max: 6, message: '名称长度 1 - 6 位', trigger: 'blur' }
  ],
  content: [{ required: true, message: '请填写标签答复', trigger: 'blur' }],
  type: [
    {
      required: true,
      message: '请选择标签类型',
      trigger: 'change'
    }
  ]
})

const formItemList = ref([])
const formItemId = ref()
const stepId = ref()

const stepNextList = ref()

/** 打开弹窗 */
const open = async (type: string, id?: object, scene: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.sceneId = scene

  // 修改时，设置数据
  if (id) {
    formData.value = await SceneApi.getSceneStepDetail(id)
    const data = await SceneApi.getSceneStepForm(id)
    stepId.value = id
    if (data) {
      formItemId.value = data.id
      if(formData.value.type == 2) {
        formItemList.value = JSON.parse(data.formContent)
      }
    }
    formLoading.value = false
  }
  stepNextList.value = await SceneApi.getSceneChildPage(2)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const stepTypeChange = (type)=>{
  if(type == 1 && formData.value.nextStepId == 0) {
    formData.value.nextStepId = undefined 
  }
}

/** 点击添加表单项 */
const addFormItem = () => {
  let obj = {
    formLabel: undefined,
    formPlaceHolder: undefined
  }
  formItemList.value.push(obj)
}

/** 删除一行formItem */
const delFormItem = (index) => {
  formItemList.value.splice(
    index,
    1
  )
}

/** 保存表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    if (formData.value.id) {
      if(formData.value.type == 2) {
        formData.value.nextStepId = 0
      }
      await SceneApi.updateStep(formData.value)
      if(formData.value.type == 2) {
        await SceneApi.updateStepForm({
          id: formItemId.value,
          formContent: JSON.stringify(formItemList.value),
          stepId: stepId.value
        })
      }
      message.success(t('common.updateSuccess'))
    } else {
      let data = await SceneApi.createStep(formData.value)
      await SceneApi.createStepForm({
        stepId: data,
        formContent: JSON.stringify(formItemList.value)
      })
      message.success(t('common.createSuccess'))
    }
    // 发送操作成功的事件
    emit('success')
    dialogVisible.value = false
    resetForm()
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    label: undefined,
    content: undefined,
    type: 1,
    nextStepId: undefined
  }
  formItemList.value.length = 0
}
</script>
